package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticsearhConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchReqVO;
import com.atguigu.gulimall.search.vo.SearchRespVO;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DuGuanghan
 * @since 2024-05-24 16:16:52
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    RestHighLevelClient client;

    @Override
    public SearchRespVO search(SearchReqVO searchReqVO) {
        // 1. 创建一个SearchRequest,用于构建查询条件
        SearchRequest search = buildSearchRequest(searchReqVO);

        // 2. 检索
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(search, ElasticsearhConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3. 封装响应结果
        return buildSearchRespVO(searchResponse, searchReqVO);
    }

    private SearchRequest buildSearchRequest(SearchReqVO searchReqVO) {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 创建query
        BoolQueryBuilder bool = QueryBuilders.boolQuery();

        // 添加模糊匹配查询
        if (!StringUtils.isEmpty(searchReqVO.getKeyword())) {
            bool.must(QueryBuilders.matchQuery("skuTitle", searchReqVO.getKeyword()));
        }
        // 增加三级分类查询
        if (searchReqVO.getCatalog3Id() != null) {
            bool.filter(QueryBuilders.termQuery("catalogId", searchReqVO.getCatalog3Id()));
        }
        // 增加库存信息查询
        if (searchReqVO.getHasStock() != null) {
            bool.filter(QueryBuilders.termQuery("hasStock", searchReqVO.getHasStock() == 1));
        }
        // 增加价格区间查询
        if (!StringUtils.isEmpty(searchReqVO.getSkuPriceRange())) {
            String skuPrice = searchReqVO.getSkuPriceRange();
            String[] s = skuPrice.split("_");

            if (s.length == 2) {
                bool.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            } else {
                if (skuPrice.startsWith("_")) {
                    bool.filter(QueryBuilders.rangeQuery("skuPrice").lte(s[0]));
                } else {
                    bool.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]));
                }
            }
        }
        // 增加品牌查询
        if (searchReqVO.getBrandId() != null && searchReqVO.getBrandId().size() > 0) {
            bool.filter(QueryBuilders.termsQuery("brandId", searchReqVO.getBrandId()));
        }
        // 增加属性查询
        if (searchReqVO.getAttrs() != null && searchReqVO.getAttrs().size() > 0) {
            for (String attr : searchReqVO.getAttrs()) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

                // 拆分属性值
                String[] attrs = attr.split("_");
                Integer attrId = Integer.valueOf(attrs[0]);
                String[] attrValues = attrs[1].split(":");

                boolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

                bool.filter(QueryBuilders.nestedQuery("attrs", boolQueryBuilder, ScoreMode.None));
            }
        }
        builder.query(bool);

        // 增加分页
        if (searchReqVO.getPageNum() != null) {
            builder.from((searchReqVO.getPageNum() - 1) * EsConstant.PAGE_SIZE);
            builder.size(EsConstant.PAGE_SIZE);
        } else {
            searchReqVO.setPageNum(1);
            builder.from(0);
            builder.size(EsConstant.PAGE_SIZE);
        }

        // 增加排序
        if (!StringUtils.isEmpty(searchReqVO.getSort())) {
            String sort = searchReqVO.getSort();
            String[] s = sort.split("_");

            SortOrder orderBy = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;

            builder.sort(s[0], orderBy);
        }

        // 增加高亮
        if (!StringUtils.isEmpty(searchReqVO.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color: red;'>");
            highlightBuilder.postTags("</b>");

            builder.highlighter(highlightBuilder);
        }

        // **************************************************** //
        // 聚合分类
        TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("category_agg").field("catalogId").size(10);
        categoryAgg.subAggregation(AggregationBuilders.terms("category_name_agg").field("catalogName").size(1));

        builder.aggregation(categoryAgg);

        // 聚合品牌
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(10);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        builder.aggregation(brandAgg);

        // 属性品牌
        NestedAggregationBuilder attrsAgg = AggregationBuilders.nested("attrs_agg", "attrs");
        TermsAggregationBuilder attrsIdAgg = AggregationBuilders.terms("attrs_id_agg").field("attrs.attrId").size(10);
        attrsIdAgg.subAggregation(AggregationBuilders.terms("attrs_name_agg").field("attrs.attrName").size(1));
        attrsIdAgg.subAggregation(AggregationBuilders.terms("attrs_value_agg").field("attrs.attrValue").size(1));

        attrsAgg.subAggregation(attrsIdAgg);
        builder.aggregation(attrsAgg);

        System.out.println(builder);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);
    }

    private SearchRespVO buildSearchRespVO(SearchResponse searchResponse, SearchReqVO searchReqVO) {
        SearchRespVO searchRespVO = new SearchRespVO();

        SearchHits hits = searchResponse.getHits();
        // 获取总记录数
        long total = hits.getTotalHits().value;
        // 计算总页数
        Long totalPages = total % EsConstant.PAGE_SIZE == 0 ? total / EsConstant.PAGE_SIZE : total / EsConstant.PAGE_SIZE + 1;
        // 当前页
        Integer pageNum = searchReqVO.getPageNum();
        // 设置页码列表
        List<Integer> pageNumList = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNumList.add(i);
        }

        // 封装SkuEsModel
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(source, SkuEsModel.class);

            if (!StringUtils.isEmpty(searchReqVO.getKeyword())) {
                // 将skuTitle设置为高亮显示
                HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                String skuTitle = highlightField.getFragments()[0].toString();

                skuEsModel.setSkuTitle(skuTitle);
            }
            skuEsModelList.add(skuEsModel);
        }

        // 获取聚合结果
        Aggregations aggregations = searchResponse.getAggregations();

        // 封装分类信息
        ParsedLongTerms categoryAgg = aggregations.get("category_agg");

        List<SearchRespVO.CatalogVO> catalogVOList = new ArrayList<>();
        for (Terms.Bucket categoryAggBucket : categoryAgg.getBuckets()) {
            SearchRespVO.CatalogVO catalogVO = new SearchRespVO.CatalogVO();

            Long categoryId = (Long) categoryAggBucket.getKeyAsNumber();

            ParsedStringTerms categoryNameAgg = categoryAggBucket.getAggregations().get("category_name_agg");
            String categoryName = categoryNameAgg.getBuckets().get(0).getKeyAsString();

            catalogVO.setCategoryId(categoryId);
            catalogVO.setCategoryName(categoryName);

            catalogVOList.add(catalogVO);
        }

        // 封装品牌信息
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");

        List<SearchRespVO.BrandVO> brandVOList = new ArrayList<>();
        Map<Long, SearchRespVO.BrandVO> brandVOMap = new HashMap<>();
        for (Terms.Bucket brandAggBucket : brandAgg.getBuckets()) {
            SearchRespVO.BrandVO brandVO = new SearchRespVO.BrandVO();

            Long brandId = (Long) brandAggBucket.getKeyAsNumber();

            ParsedStringTerms brandImgAgg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();

            ParsedStringTerms brandNameAgg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();

            brandVO.setBrandId(brandId);
            brandVO.setBrandImg(brandImg);
            brandVO.setBrandName(brandName);

            brandVOList.add(brandVO);
            brandVOMap.put(brandId, brandVO);
        }

        // 封装属性信息
        ParsedNested attrsAgg = aggregations.get("attrs_agg");
        ParsedLongTerms attrsIdAgg = attrsAgg.getAggregations().get("attrs_id_agg");

        List<SearchRespVO.AttrVO> attrVOList = new ArrayList<>();
        Map<Long, SearchRespVO.AttrVO> attrVOMap = new HashMap<>();
        for (Terms.Bucket attrsAggBucket : attrsIdAgg.getBuckets()) {
            SearchRespVO.AttrVO attrVO = new SearchRespVO.AttrVO();

            Long attrId = (Long) attrsAggBucket.getKeyAsNumber();

            ParsedStringTerms attrsNameAgg = attrsAggBucket.getAggregations().get("attrs_name_agg");
            String attrName = attrsNameAgg.getBuckets().get(0).getKeyAsString();

            ParsedStringTerms attrsValueAgg = attrsAggBucket.getAggregations().get("attrs_value_agg");
            List<String> attrValueList = attrsValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());

            attrVO.setAttrId(attrId);
            attrVO.setAttrName(attrName);
            attrVO.setAttrValue(attrValueList);

            attrVOList.add(attrVO);
            attrVOMap.put(attrId, attrVO);
        }

        // 封装面包屑导航信息
        List<SearchRespVO.NavVO> navVOList = new ArrayList<>();
        List<Long> attrChecked = new ArrayList<>();
        if (!CollectionUtils.isEmpty(searchReqVO.getAttrs())) {
            searchReqVO.getAttrs().forEach(attr -> {
                // {attr_id}_{attr_value}:{attr_value}:...
                String[] s = attr.split("_");
                // 获取属性ID对应的属性名
                String attrName = attrVOMap.get(Long.parseLong(s[0])).getAttrName();

                SearchRespVO.NavVO navVO = new SearchRespVO.NavVO();
                navVO.setName(attrName);
                navVO.setValue(s[1]);
                navVO.setLinkParam("attrs=" + attr);

                navVOList.add(navVO);
                attrChecked.add(Long.parseLong(s[0]));
            });
        }
        if (!CollectionUtils.isEmpty(searchReqVO.getBrandId())) {
            searchReqVO.getBrandId().forEach(brandId -> {
                String brandName = brandVOMap.get(brandId).getBrandName();

                SearchRespVO.NavVO navVO = new SearchRespVO.NavVO();
                navVO.setName("品牌");
                navVO.setValue(brandName);
                navVO.setLinkParam("brandId=" + brandId);

                navVOList.add(navVO);
            });
        }

        //***********************************************************//
        // 封装SearchRespVO
        searchRespVO.setAttrs(attrVOList);
        searchRespVO.setBrands(brandVOList);
        searchRespVO.setCatalogs(catalogVOList);
        searchRespVO.setPageNum(pageNum);
        searchRespVO.setTotal(total);
        searchRespVO.setTotalPages(totalPages.intValue());
        searchRespVO.setSkuEsModelList(skuEsModelList);
        searchRespVO.setPageNumList(pageNumList);
        searchRespVO.setNavs(navVOList);
        searchRespVO.setAttrChecked(attrChecked);
        //***********************************************************//

        return searchRespVO;
    }
}
